import shell from 'shelljs';
import chalk from 'chalk'
import os from 'os';
import path from 'path'

// config
const bucket = 'oss://nswda-assets'
const ossutilconf_path = './utils/assets-async/bin/ossutilconfig'
const bin = getBinPathByOS()


/**
 * 通过系统类型调用不同的ossutil
 * @returns string
 */
function getBinPathByOS() {
    const ostype = os.type();
    const binfile = ostype === 'Windows_NT' ? 'ossutil64.exe' : 'ossutilmac64'
    return `./utils/assets-async/bin/${binfile}`
}

/**
 * 同步某一个文件夹
 * @param {string} folder_name 要同步的文件夹名字
 */
function asyncFolder(folder_name) {
    console.log('\n')
    console.log(chalk.bgMagentaBright(`⭐️[${folder_name} downloading...]`))

    const bin_fullpath = path.resolve(bin);
    const ossutilconf_fullpath = path.resolve(ossutilconf_path)
    const bucket_fullpath = `${bucket}/${folder_name}`
    const current_fullpath = path.resolve('./')

    os.type() === 'Windows_NT' && shell.exec('chcp 65001')
    const cmd = `${bin_fullpath} -c ${ossutilconf_fullpath} cp -r ${bucket_fullpath} ${current_fullpath} --update`
    console.log('cmd:',cmd)
    shell.exec(cmd)
}

/**
 * 同步几组文件夹
 * @param {array<string>} folder_paths 同步数个文件夹
 */
function asyncAllFolder(folder_paths) {
    try {
        folder_paths.forEach(path => asyncFolder(path)) //exec

        console.log('\n')
        console.log(chalk.bgGreenBright('async finish!'))
        console.log('\n')
    } catch (err) {
        console.error(chalk.red('async failed!'), err)
    }
}

/**
 * 主函数
 */
function main() {
    const allFolders = ['audio', 'img', 'fonts', 'icon', 'movies','zh_hant_sources']
    asyncAllFolder(allFolders)
}
main()